package com.epro.dx.widget;


import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.epro.dx.R;

/**
 * 自定义加减编辑框控件
 * 
 * @author hjd008
 * @version [版本号, 2015-1-9]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class AddSubtracterView extends RelativeLayout {

	private Context mContext;

	/**
	 * 加号
	 */
	private ImageButton btnAdd;

	/**
	 * 减号
	 */
	private ImageButton btnSub;

	/**
	 * 编辑框
	 */
	private EditText editNumber;

	/**
	 * 数字变化监听
	 */
	private OnNumChangeListener onNumChangeListener;

	/**
	 * 个数
	 */
	private int number = 1;

	/**
	 * 可输入的最大数 9999999
	 */
	private int maxNumber = 9999999;
	
	private int limitNum;
	
	private AlertDialog dialog;
	private boolean canShowDialog = true;//是否能够显示快速编辑数量的弹窗

	public AddSubtracterView(Context context) {
		this(context, null);
	}

	public AddSubtracterView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	/**
	 * AttributeSet：将自定义控件类中变量与attrs.xml中的属性连接起来。
	 * defStyle：指定view的默认style的，如果是0，那么将不会应用任何默认（或者叫缺省）的style。
	 * 另外这个参数可以是一个属性指定的style引用，也可以直接是一个显式的style资源。
	 */
	public AddSubtracterView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.mContext = context;
		setWillNotDraw(false);
		initView();
	}

	/**
	 * 初始化试图
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void initView() {
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.widget_addandsub, this);
		btnAdd = (ImageButton) findViewById(R.id.btn_add);
		btnSub = (ImageButton) findViewById(R.id.btn_subtract);
		editNumber = (EditText) findViewById(R.id.edit_number);
		editNumber.setText(String.valueOf(number));

		btnAdd.setOnClickListener(new OnButtonClickListener());
		btnSub.setOnClickListener(new OnButtonClickListener());
//		editNumber.addTextChangedListener(new OnTextChangeListener());
		editNumber
				.setOnFocusChangeListener(new OnEditTextFocusChangeListener());
		//设置文本输入框点击事件
		editNumber.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 点击文本框显示弹窗支持数量快速编辑
				showEditNumberDialog();
			}
		});
	}

	public void setCanShowDialog(boolean canShow){
		this.canShowDialog = canShow;
	}
	
    /**
     * 显示快速编辑数量的弹窗
     */
    protected void showEditNumberDialog() {
    	if(!canShowDialog){
    		return;
    	}
		// 弹窗显示编辑框
		Builder builder = new AlertDialog.Builder(mContext);
		final EditText view = new EditText(mContext);
		view.setInputType(InputType.TYPE_CLASS_NUMBER);
		view.setFilters(new InputFilter[]{new InputFilter.LengthFilter((""+maxNumber).length())});
		view.setText(getNum()+"");
		view.setSelection((getNum()+"").length());
		builder.setTitle("Please enter the quantity");
		builder.setView(view);
		builder.setNegativeButton("Confirm", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 将编辑框中的数字设置到中间的数量显示框中
				String quatity = view.getText().toString().trim();
				if(!TextUtils.isEmpty(quatity)&&quatity.length()<Integer.MAX_VALUE){
					setNum(Integer.parseInt(quatity));
					if (null != onNumChangeListener) {
						onNumChangeListener.onNumChange(AddSubtracterView.this,
								number,true,false);
					}
				}
			}
		});
		builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// 取消，不做操作，隐藏弹窗
				dialog.dismiss();
			}
		});
		dialog = builder.create();
		dialog.show();
	}

	/**
     * 设置商品库存量
     * @param limitNum
     */
	public void setLimitNum(int limitNum) {
		this.limitNum = limitNum;
	}
	
	public int getLimitNum(int limitNum){
		return limitNum;
	}

	/**
	 * 设置editText中的值(1->Int.MAX)
	 * 
	 * @param num
	 */
	public void setNum(int num) {
		if (num >= 1) {
			editNumber.setText(String.valueOf(num));
			number = num;
		}
	}

	/**
	 * 获取editText中的值
	 * 
	 * @return
	 */
	public int getNum() {
		return number;
	}

	/**
	 * 设置EditText文本变化监听
	 * 
	 * @param onNumChangeListener
	 */
	public void setOnNumChangeListener(OnNumChangeListener onNumChangeListener) {
		this.onNumChangeListener = onNumChangeListener;
	}

	/**
	 * 加减按钮事件监听器
	 * 
	 * @author hjd008
	 * @version [版本号, 2015-1-9]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	private class OnButtonClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			String numString = editNumber.getText().toString();
			if (TextUtils.isEmpty(numString) || number <= 0) {
				setNum(1);
				
			}
			// 点击加号
			if (v.getId() == R.id.btn_add) {
				// 当商品数量达到最大值或库存值时
				if (limitNum == -1) {
					if (number >= maxNumber) {
						return;
					}
				} else {
					if (limitNum <= 0 || number >= limitNum) {
//						Toast.makeText(mContext, mContext.getString(R.string.sku_limit_suggest, limitNum), 0).show();
						return;
					}
				}
				setNum(++number);
				if (null != onNumChangeListener) {
					onNumChangeListener.onNumChange(AddSubtracterView.this,
							number,true,false);
				}
			} else if (v.getId() == R.id.btn_subtract) {
				if (number <= 1) {
					onNumChangeListener.toDeleteItem(AddSubtracterView.this);
					return;
				}
				setNum(--number);
				if (null != onNumChangeListener) {
					onNumChangeListener.onNumChange(AddSubtracterView.this,
							number,false,false);
				}

			}
		}
	}

	/**
	 * EditText输入内容变化事件监听器
	 * 
	 * @author hjd008
	 * @version [版本号, 2015-1-9]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	private class OnTextChangeListener implements TextWatcher {
		@Override
		public void afterTextChanged(Editable s) {
			String numString = s.toString();
			if (!TextUtils.isEmpty(numString)) {
				int numInt = Integer.parseInt(numString);
				if (numInt >= 1 && numInt != number) {
					number = numInt >= maxNumber ? maxNumber : numInt;
					boolean isAdd=false;
					if(numInt<=number){
						isAdd=false;
					}else{
						isAdd=true;
					}
					setNum(number);
					// 设置EditText光标位置 为文本末端
					editNumber.setSelection(editNumber.getText().toString()
							.length());
					if (onNumChangeListener != null) {
						onNumChangeListener.onNumChange(AddSubtracterView.this,
								number,isAdd,false);
					}
				}
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

	}

	/**
	 * EditText焦点变化事件监听器
	 * 
	 * @author hjd008
	 * @version [版本号, 2015-1-9]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	private class OnEditTextFocusChangeListener implements
			OnFocusChangeListener {

		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			if (!hasFocus) {
				String numString = editNumber.getText().toString();
				if (TextUtils.isEmpty(numString)) {
					setNum(1);
				}
			}
		}

	}

	public int getMaxNumber() {
		return maxNumber;
	}

	public void setMaxNumber(int maxNumber) {
		this.maxNumber = maxNumber;
	}

	/**
	 * 设置加减按钮是否可点击
	 * @param add 加号按钮
	 * @param sub 减号按钮
	 */
	public void setButtonClickable(boolean add,boolean sub){
		btnAdd.setClickable(add);
		btnSub.setClickable(sub);
	}
	
	/**
	 * 编辑框数字变化接口
	 * 
	 * @author hjd008
	 * @version [版本号, 2015-1-9]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	public interface OnNumChangeListener {
		/**
		 * sku数量改变
		 * @param view 
		 * @param num sku的数量（View 中的num）
		 * @param isAdd 是否为+的点击
		 * @param isLimitChange 是否是因为库存不足而改变的数量
		 */
		public void onNumChange(View view, int num,boolean isAdd,boolean isLimitChange);
		
		public void toDeleteItem(View view);
	}

}
